import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2022-11-27
 * Time:15:07
 */
@WebServlet("/showRequest")
public class ShowRequestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // resp 是响应对象, setContentType, 给响应的 ContentType 设置了值. html
        // 声明响应 body 是 html 结构的数据.

        resp.setContentType("text/html");


        StringBuilder stringBuilder = new StringBuilder();
        //返回请求协议的名称和版本:HTTP/1.1
        stringBuilder.append(req.getProtocol());
        stringBuilder.append("<br>");
        //返回请求的 HTTP 方法的名称，例如，GET、POST 或 PUT
        stringBuilder.append(req.getMethod());
        stringBuilder.append("<br>");
        //从协议名称直到 HTTP 请求的第一行的查询字符串中，返回该请求的 URL 的一部分
        stringBuilder.append(req.getRequestURI());
        stringBuilder.append("<br>");
        //返回指示请求上下文的请求 URI 部分
        stringBuilder.append(req.getContextPath());
        stringBuilder.append("<br>");
        //返回包含在路径后的请求 URL 中的查询字符串
        stringBuilder.append(req.getQueryString());
        stringBuilder.append("<br>");

        //把请求的 header 也拼进来
        //返回一个枚举，包含在该请求中包含的所有的头名
        Enumeration<String> headerNames = req.getHeaderNames();

        while(headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            String value = req.getHeader(name);
            stringBuilder.append(name + ": " + value);
            stringBuilder.append("<br>");
        }

        resp.getWriter().write(stringBuilder.toString());
    }
}
